package com.wnxy.pawnbackgroundsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wnxy.pawnbackgroundsystem.commons.*;
import com.wnxy.pawnbackgroundsystem.dto.userDto.AccountLogin;
import com.wnxy.pawnbackgroundsystem.dto.userDto.PhoneLogin;
import com.wnxy.pawnbackgroundsystem.entity.QQMessage;
import com.wnxy.pawnbackgroundsystem.entity.User;
import com.wnxy.pawnbackgroundsystem.dao.UserMapper;
import com.wnxy.pawnbackgroundsystem.exception.DemoRuntimeException;
import com.wnxy.pawnbackgroundsystem.param.UserParam;
import com.wnxy.pawnbackgroundsystem.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author Lucas
 * @since 2021-10-14
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private StringRedisTemplate srt;

    //QQ登陆
    public String qqLogin(String code){
        log.info("开始执行QQ登陆：参数= {}",code);
        QQMessage qqMessage = QQMessageUtil.getQQMessage(code);
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("user_qq_openid",qqMessage.getOpenId());
        User user = userMapper.selectOne(qw);
        if (null == user) {
            return QQMessageUtil.qqWindon();
        }

        if (null == user.getUserQqNickname()){
            user.setUserQqNickname(qqMessage.getNickname());
            user.setUserQqImg(null != qqMessage.getFigureurl_qq()?qqMessage.getFigureurl_qq():null != qqMessage.getFigureurl_qq_1()?qqMessage.getFigureurl_qq_1():qqMessage.getFigureurl_qq_2());
        }
        UserParam userParam = updateLoginSuccess(user,User.LOGIN_QQ);//修改登陆成功后的数据
        String jwt = JwtUtils.createJWT(userParam);
        ServletApiUtil.setResponseHander(JwtUtils.AUTH_TOKEN_NAME,jwt);
        String qq = QQMessageUtil.qqWindon(QQMessageUtil.QQ_LOGIN_SUCCESS, jwt);
        return qq;
    }
    //账号登陆
    public UserParam accountLogin(AccountLogin accountLogin){
        log.info("开始执行账号登陆：参数= {}",accountLogin);
        User user = findUserName(accountLogin.getUsername());
        if (!user.getUserPassword().equals(accountLogin.getPassword())) {
            throw new DemoRuntimeException("密码不正确");
        }
        UserParam userParam = updateLoginSuccess(user,User.LOGIN_ACCOUNT);//修改登陆成功后的数据
        return userParam;
    }

    //手机号登陆
    public UserParam phoneLogin(PhoneLogin phoneLogin){
        log.info("开始执行手机号登陆：参数= {}",phoneLogin);
        chekeCode(phoneLogin.getCode(),phoneLogin.getPhone());
        User user = findPhone(phoneLogin.getPhone());
        if (!user.getUserPassword().equals(phoneLogin.getPassword())) {
            throw new DemoRuntimeException("密码不正确");
        }
        UserParam userParam = updateLoginSuccess(user,User.LOGIN_PHONE);//修改登陆时间
        return userParam;
    }
    //查询当前登陆用户信息
    public UserParam findUser(){
        User user = ServiceImplUtil.getJwtUtilUser(JwtUtils.AUTH_TOKEN_NAME);
        UserParam userById = findUserById(user.getUserId());
        return userById;
    }

    //手机号发送验证码
    public String phoneCode(String phone){
        log.info("开始执行手机号发送验证码：参数= {}",phone);
        User user = findPhone(phone);
        String code = ((int)(Math.random()*9)+1)+""+(int)(Math.random()*10)+""+(int)(Math.random()*10)+""+(int)(Math.random()*10);;
        System.out.println("手机验证码："+code);
        srt.opsForValue().set("code:user:" + phone,code,300, TimeUnit.SECONDS);
        return code;
    }

    //检验验证码
    public void chekeCode(String code,String phone){
        log.info("开始执行手机验证码比较：参数= {},{}",code,phone);
        String rCode = srt.opsForValue().get("code:user:" + phone);
        if (null == rCode) {
            throw new DemoRuntimeException("验证码已过期");
        }
        if(!code.equals(rCode)){
            throw new DemoRuntimeException("验证码不正确");
        }
    }
    //登陆成功后修改登陆参数修改
    public UserParam updateLoginSuccess(User user,String loginType){
        log.info("登陆成功修改状态：参数={},{}",user,loginType);
        Long systemTimeStamp = DateUtil.getSystemTimeStamp();
        user.setUserLoginTime(systemTimeStamp);
        user.setUserLoginType(loginType);
        userMapper.updateById(user);
        UserParam userParam = new UserParam();
        BeanUtils.copyProperties(user, userParam);
        return userParam;
    }

    //账号查询
    public User findUserName(String account){
        log.info("开始执行账号是否存在：参数= {}",account);
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("user_account",account);
        User user = userMapper.selectOne(qw);
        if (null == user){
            throw new DemoRuntimeException("用户名不存在");
        }
        return user;
    }
    //id查询
    public UserParam findUserById(Integer userId){
        log.info("开始执行获取用户信息：参数= {}",userId);
        User user = userMapper.selectById(userId);
        UserParam userParam = new UserParam();
        BeanUtils.copyProperties(user,userParam);
        return userParam;
    }
    //手机号查询
    public User findPhone(String phone){
        log.info("开始执行手机号是否存在：参数= {}",phone);
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("user_phone",phone);
        User user = userMapper.selectOne(qw);
        if (null == user){
            throw new DemoRuntimeException("手机号不存在");
        }
        return user;
    }

}
